package us.sunrisemorning.bilibili_live_chat.ws;

import cn.hutool.core.util.ZipUtil;
import us.sunrisemorning.bilibili_live_chat.Constants;

import java.nio.ByteBuffer;

public class WebSocketMessage {
    private String body;
    private int operation;

    public WebSocketMessage(String body, int operation) {
        this.body = body;
        this.operation = operation;
    }

    public WebSocketMessage(ByteBuffer byteBuffer) {
        decode(byteBuffer);
    }

    private void decode(ByteBuffer byteBuffer) {
        operation = byteBuffer.getInt(Constants.WS_OPERATION_OFFSET);
        short version = byteBuffer.getShort(Constants.WS_VERSION_OFFSET);

        int bodyLength = byteBuffer.getInt() - Constants.WS_PACKAGE_HEADER_TOTAL_LENGTH;
        byte[] bodyArray = new byte[bodyLength];
        byteBuffer.position(Constants.WS_PACKAGE_HEADER_TOTAL_LENGTH);
        byteBuffer.get(bodyArray);
        if (Constants.WS_BODY_PROTOCOL_VERSION_ZLIB == version) {
            bodyArray = ZipUtil.unZlib(bodyArray);
            decode(ByteBuffer.wrap(bodyArray));
        } else {
            body = new String(bodyArray);
        }
    }

    public byte[] toByteArrayMessage() {
        byte[] bodyArray = body.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(Constants.WS_PACKAGE_HEADER_TOTAL_LENGTH + bodyArray.length);
        byteBuffer.putInt(Constants.WS_PACKAGE_HEADER_TOTAL_LENGTH + bodyArray.length);
        byteBuffer.putShort(Constants.WS_PACKAGE_HEADER_TOTAL_LENGTH);
        byteBuffer.putShort(Constants.WS_HEADER_DEFAULT_VERSION);
        byteBuffer.putInt(operation);
        byteBuffer.putInt(Constants.WS_HEADER_DEFAULT_SEQUENCE);
        byteBuffer.put(bodyArray);
        return byteBuffer.array();
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public int getOperation() {
        return operation;
    }

    public void setOperation(int operation) {
        this.operation = operation;
    }
}
